/*
 *  Copyright (c) 2018. AnStudio + Medical Plus Project
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.anstudio.app.lhasa.common.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import java.lang.reflect.Field;

public class ObjectUtils {
    private static Logger logger = LogManager.getLogger(ObjectUtils.class);

    public static final JSONObject formatJSON(Object obj) {
        JSONObject ret = new JSONObject();
        try {
            for (Field field : obj.getClass ().getDeclaredFields()) {
                field.setAccessible(true);
                ret.append(field.getName(), field.get(obj));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            return ret;
        }
    }

    public static Object cloneFrom(Object src, Object dest) {
        if (src == null || !src.getClass().equals(dest.getClass())) {
            return null;
        }

        for (Field field : src.getClass ().getDeclaredFields()) {
            field.setAccessible(true);
            if (field.getType().equals(String.class)) {
                try {
                    field.set(dest
                            , StringUtils.isEmpty((String) field.get(src)) ?
                                    field.get(dest) : field.get(src));
                } catch (IllegalAccessException e) {
                    logger.error(e);
                    continue;
                }
            }

            if (field.getType().equals(Integer.class)
                    || field.getType().equals(int.class)) {
                try {
                    field.set(dest, field.get(src) == null ?
                            -1 : field.get(src));
                } catch (IllegalAccessException e) {
                    logger.error(e);
                    continue;
                }
            }
        }

        return dest;
    }

    public static final String toJsonString(Object obj) {
        JSONObject out = formatJSON(obj);

        return out == null ? obj.toString() : obj.toString();
    }

}
